package com.example.springLearning.part16.config;

import com.example.springLearning.part16.error.NotAllowException;
//import com.sun.deploy.net.HttpResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter
@Slf4j
@Component
public class PermissionFilter implements Filter {

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String token = httpServletRequest.getHeader("token");
        if ("111111".equals(token)) {
//            log.info("throw NotAllowException");
//            throw new NotAllowException();
            resolver.resolveException(httpServletRequest, httpResponse, null, new NotAllowException());
            return;
        }
        chain.doFilter(request, response);
    }
}
